package com.rndemo.db;


import android.os.Handler;
import android.os.HandlerThread;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * Created by tzj on 2018/5/28.
 */
public class Where {
    public static Handler mHandler = new Handler();
    public static Handler dbHandler;
    static {
        HandlerThread dbHandlerThread = new HandlerThread("dbHandlerThread");
        dbHandlerThread.start();
        dbHandler = new Handler(dbHandlerThread.getLooper());
    }

    private WeakReference<BaseDB> weakReference;
    private String where;
    private Object data;

    public Where(BaseDB baseDB,String where, String... data) {
        weakReference = new WeakReference<BaseDB>(baseDB);
        this.where = where;
        this.data = data;
    }

    public void insert(final ICallBack callback){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                BaseDB baseDB = weakReference.get();
                if(baseDB!=null){
                    long insert = baseDB.insert(where,data);
                    callback.result(null, insert);
                }
            }
        };
        dbHandler.post(runnable);
    }
    public void delete(final ICallBack callback){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                BaseDB baseDB = weakReference.get();
                if(baseDB!=null){
                    int delete = baseDB.delete(where, (String[]) data);
                    callback.result(null,delete);
                }
            }
        };
        dbHandler.post(runnable);
    }
    public void select(final ICallBack callback) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                BaseDB baseDB = weakReference.get();
                if(baseDB!=null){
                    final List select = baseDB.select(where, (String[]) data);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.result(select,select.size());
                        }
                    });
                }
            }
        };
        dbHandler.post(runnable);
    }
    public void update(final ICallBack callback) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                BaseDB baseDB = weakReference.get();
                if(baseDB!=null){
                    int update = baseDB.update(where, (String[]) data);
                    callback.result(null,update);
                }
            }
        };
        dbHandler.post(runnable);
    }



}
